/*
 * 文件名：PayController.java
 * 版权：
 * 描述：TODO
 * 修改人：zuo liubo
 * 修改时间：2013-3-7 上午10:45:05
 */
package com.scpii.api.controller.ec;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scpii.api.common.base.BaseController;
import com.scpii.api.common.exception.EcException;
import com.scpii.api.domain.ec.Order;
import com.scpii.api.persistence.ec.OrderMapper;
import com.scpii.api.service.ec.PayService;
import com.scpii.api.util.PrincipalUtil;

/**
 * @description 支付类控制器
 * @author zuo liubo
 * @date 2013-3-7
 */
@Controller
@RequestMapping("/ec/pay")
public class PayController extends BaseController {
	private Log logger = LogFactory.getLog(PayController.class);

	@Resource
	private PayService payService;
	@Resource
	private OrderMapper orderMapper;

	/**
	 * 支付订单
	 * 
	 * @param orderId
	 *            订单ID
	 * @return 返回一个URL地址，客户端使用这个URL地址进行支付
	 * @throws Exception
	 */
	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(value = "/order/{orderId}", method = RequestMethod.GET)
	@ResponseBody
	public Object pay(@PathVariable("orderId") Long orderId) throws Exception {
		Long userId = PrincipalUtil.getPrincipal().getId();
		List<Object> result = new ArrayList<Object>();
		// TODO 更新订单支付状态为付款中
		try {
			Object payLink = payService.payOrder(orderId, userId);
			logger.info("payLink:" + payLink);
			result.add(payLink);
		} catch (Exception e) {
			Order order = new Order();
			order.setOrderId(orderId);
			List<Order> orders = orderMapper.selectOrderBySelective(order);
			if (orders.size() == 1) {
				order = orders.get(0);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("orderId", order.getOrderId());
				map.put("orderSn", order.getOrderSn());
				map.put("paymentType", order.getPaymentType());
				map.put("status", 1008);
				map.put("statusDescription", "服务器内部错误");
				if(e instanceof EcException){
					map.put("status", ((EcException) e).getStatus().getValue());
					map.put("statusDescription", e.getMessage());
				}
				map.put("totalPrice", order.getTotalPrice());
				result.add(map);
			}
		} 
		return result;
	}
}
